package com.smartum.mpr.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.smartum.mpr.client.services.ImageService;
import com.smartum.mpr.server.utils.ConnectionPropertyReader;
import com.smartum.mpr.server.utils.JSONHelper;
import com.smartum.mpr.shared.Image;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 */
public class ImageServiceImpl extends RemoteServiceServlet implements ImageService {

    public void submitImages(int pageSize, Long[] acceptIds, Long[] declineIds) throws IOException {
        final JSONObject webRequestHeader = buildModerateJSON(pageSize, new Timestamp(0).getTime(), acceptIds, declineIds);
        final HttpURLConnection conn = JSONHelper.getHttpURLConnection(ConnectionPropertyReader.getModerateImagesURL());

        try {
            conn.connect();
        } catch (IOException e) {
        }

        JSONHelper.proceedRequest(webRequestHeader, conn);
    }

    public List<Image> getImages(int pageSize, long timestamp) throws IOException {

        final JSONObject webRequestHeader = JSONHelper.buildImgRetrievalJSON(pageSize, timestamp, this.getThreadLocalRequest());

        final HttpURLConnection conn = JSONHelper.getHttpURLConnection(ConnectionPropertyReader.getUnconfirmedImagesURL());
        try {
            conn.connect();
        } catch (IOException e) {
        }

        final String response = JSONHelper.proceedRequest(webRequestHeader, conn);
        return parseGetImageResponse(response);
    }

    public long getTotalUnmoderateImages() throws IOException {
        final JSONObject webRequestHeader = JSONHelper.buildImgRetrievalJSON(0, new Timestamp(0).getTime(), this.getThreadLocalRequest());

        final HttpURLConnection conn = JSONHelper.getHttpURLConnection(ConnectionPropertyReader.getUnconfirmedImagesURL());
        try {
            conn.connect();
        } catch (IOException e) {
        }

        final String response = JSONHelper.proceedRequest(webRequestHeader, conn);
        return parsePageNumberRespone(response);
    }

    public void removeTempImage(String imageName) throws IOException {
        final String realPath = getServletContext().getRealPath("/");
        File uploadedFile = new File(realPath + "images" + File.separator + imageName);

        if (!NewsServiceImpl.NO_PHOTO_NAME.equals(imageName)) {
            uploadedFile.delete();
        }
    }

    private long parsePageNumberRespone(String response) {
        long result = 0;
        final JSONObject responseJSON;
        try {
            responseJSON = JSONHelper.getResponseJSON(response);
            result = (Long) responseJSON.get("unconfirmed_images_number");

        } catch (ParseException e) {
        }

        return result;
    }

    private List<Image> parseGetImageResponse(String response) {
        List<Image> result = new ArrayList<Image>();
        final JSONObject responseJSON;
        try {
            responseJSON = JSONHelper.getResponseJSON(response);


            final String images = responseJSON.get("images").toString();
            JSONParser imageResponseParser = new JSONParser();
            final JSONArray imagesCollection = (JSONArray) imageResponseParser.parse(images);
            for (int i = 0; i < imagesCollection.size(); i++) {

                final JSONObject jsonObject = (JSONObject) imagesCollection.get(i);
                final Image image = new Image();
                image.setId((Long) jsonObject.get(JSONHelper.IMAEG_ID));
                image.setName((String) jsonObject.get(JSONHelper.IMAEG_USERNAME));
                final String originalImage = (String) jsonObject.get(JSONHelper.IMAEG_URL);
                image.setImageUrl(originalImage);
                image.setImageUrlLittle((String) jsonObject.get(JSONHelper.IMAEG_URL_LITTLE));
                image.setTimestamp((Long) jsonObject.get(JSONHelper.IMAEG_TIMESTAMP));

                result.add(image);
            }
        } catch (ParseException e) {
        }

        return result;
    }

    private JSONObject buildModerateJSON(int pageSize, long timestamp, Long[] acceptIds, Long[] declineIds) throws IOException {
        final HttpServletRequest request = this.getThreadLocalRequest();
        final HttpSession session = request.getSession(false);

        final Object authToken = session.getAttribute(JSONHelper.AUTH_TOKEN);
        final JSONObject webRequestHeader = JSONHelper.getWebRequestHeader(authToken);

        JSONObject requestObject = new JSONObject();

        JSONArray confirmJsonArray = new JSONArray();
        confirmJsonArray.addAll(Arrays.asList(acceptIds));

        JSONArray declineJsonArray = new JSONArray();
        declineJsonArray.addAll(Arrays.asList(declineIds));

        requestObject.put("confirmed", confirmJsonArray);
        requestObject.put("unconfirmed", declineJsonArray);

        webRequestHeader.put("request", requestObject);
        return webRequestHeader;
    }


}
